<template>
  <eui-page-frame :topHeight="100">
    <template #top>
      <view style="width: auto; background-color: white">
        <eui-nav-bar
            title="调拨申请单"
            backgroundColor="white"
            color="black"
            rightIcon=""
        />
      </view>
    </template>
    <eui-page-content>
      <eui-anchor-scrollview
          :tab-list="data.tabList"
          :tab-height="104"
          :btnheight="120"
      >
        <!-- 第一个tab的内容 -->
        <template #content-0>
          <eui-statecard label="商品信息" state="待收货" type="commodity" @change="cardchange">
            <searchs @submit="searchlist"/>
            <eui-commodity-information
                v-for="(item, index) in data.ReturnObject"
                v-show='filtervalue(item.c_name)'
                :styletype="data.documnettype == 2"
                :isshowcheckout="data.documnettype == 2"
                :name="item.c_name"
                label="调拨数量"
                :number="index + 1"
                :key="index"
                :mondata="item"
                @checkout="checkout"
            >
              <view class="flex first">
                <!-- <view>货号：{{ item.c_gcode }}</view> -->
                <view>编码：{{ item.c_gcode }}</view>
              </view>
              <view class="flex second">
                <!-- <view>合理库存</view> -->
                <view>系统库存:{{ item.c_number }}</view>
                <view>在途库存:{{ item.c_onway }}</view>
              </view>
              <view class="flex third">
                <view>昨</view>
                <view>均</view>
                <view>环</view>
              </view>
              <template #inputnumber>
                <eui-inputnumber
                    v-model="item.c_qtty"
                    :styletype="data.documnettype == 2"
                    :value="item.c_qtty"
                    jldw=""
                    @input="(e)=> uploadgoodcar(item,e.detail.value) "
                />
              </template>
            </eui-commodity-information>
            <nodata v-if="data.ReturnObject.length == 0 || data.isnodata"/>
            <view class="comhj" v-else>
              <view>合计：</view>
              <view>{{ amountto }}</view>
            </view>
          </eui-statecard>
        </template>

        <!-- 第二个tab的内容 -->
        <template #content-1>
          <view class="card">
            <eui-title label="表单信息"/>
            <eui-fromtable ref="fromtable" :fromlist="data.fromlist" @uploadimage='uploadimage'
                           @callbackfun='callbackfun'/>
          </view>
        </template>

        <!-- 第三个tab的内容 -->
        <template #content-2>
          <view class="card" style="margin-bottom: 140rpx">
            <eui-title label="处理记录"/>
            <eui-newstep
                style="margin-top: 30rpx"
                :stepslist="data.stepslist"
            />
          </view>
        </template>
      </eui-anchor-scrollview>
    </eui-page-content>
  </eui-page-frame>
  <buttons
      type="fromtwo"
      @callback="callback"
      :configuration="data.configuration"
  />
  <popupfrom ref="refpopupfrom" title="评论"/>
</template>

<script setup lang="ts">
import { onShow ,onLoad} from "@dcloudio/uni-app";
import { ref, reactive , computed, type Ref } from "vue";
import useService from "@/hooks/useService";
import buttons from "@/pages/BusiViews/components/buttons.vue";
import searchs from "@/pages/BusiViews/components/searchs.vue";
import nodata from "@/pages/BusiViews/components/nodata.vue";
import popupfrom from "@/pages/BusiViews/components/popupfrom.vue";

import { storeToRefs } from "pinia";
import { useThemeStore } from "@/store/themeStore";
import { getRdsUrl, rdsRequest } from "@/hooks/rdsServices";
import { useReceiptStore } from '@/store/useReceiptStore';
import { useMainStore } from '@/store/modules/store';
import { getBillStatus, AUDIT_STATUS, APPROVAL_STATUS } from '@/pages/BusiViews/hooks/states';
import { convertDraft } from '@/pages/BusiViews/hooks/convert';
import useUpload from '@/hooks/useUpload';
const mainStore = useMainStore();
const rdsUrl = getRdsUrl();
const themeStore = useThemeStore(); // 主题
const { theme } = storeToRefs(themeStore);
const fromtable: any = ref(null);
const refpopupfrom: any= ref(null);

// 购物车相关
const receiptStore = useReceiptStore();
const {cartList, isBack, fromData: storefromdata} = storeToRefs(receiptStore);
const themeColor = computed(() =>
    theme.value === "theme-blue" ? "#02B7E6" : "#FF6430"
);
const service = useService({prefix: "apiApi"});
const data = reactive({
  documnettype: 1, //1:调拨 2:反调拨
  activename: "商品信息",
  value: 11,
  tabList: [{name: "商品信息"}, {name: "表单信息"}, {name: "处理记录"}],
  stepslist: [
    {
      title: "表单创建",
      name: "张磊",
      time: "2021.1.1",
      state: 1,
    },
    {
      title: "表单创建1",
      name: "张磊",
      comment: "张磊张磊张磊张磊张磊张磊张磊张磊张磊",
      time: "2021.1.1",
      state: 4,
    },
    {
      title: "表单创建2",
      name: "张磊",
      time: "2021.1.1",
      state: 2,
    },
  ],
  barFixed: true,
  barHeight: "44",
  barTop: 0,
  isnodata: false,
  iconShow: true,
  barId: "0",
  fromlist: {
    c_mk_userno: {
      label: "录入人",
      type: "text",
      value: mainStore.loginInfo.sUserName,
      disabled: true,
    },
    c_mk_dt: {
      label: "录入时间",
      type: "text",
      value: "2025-01-08 10:10:00",
      disabled: true,
    },
    c_s_store_id: {},
    c_dname: {
      label: "所属部门",
      type: "funselect",
      funname: 'gednamet',
      key: 'c_name',
      placeholder: "请选择所属部门",
      value: [],
    },
    md: {
      label: "调出门店",
      placeholder: "请选择调出门店",
      type: "funselect",
      funname: 'getmd',
      value: '',
    },
    c_note: {
      label: "备注",
      type: "textarea",
      placeholder: "请输入备注",
      value: "",
    }
  },
  billStatus: {
    auditStatus: AUDIT_STATUS.PENDING,  // 初始状态为待提交
    approvalStatus: APPROVAL_STATUS.PENDING
  },
  configuration: [
    // {
    //   name: "作废",
    //   fun: "void",
    //   show: computed(() => getBillStatus(data.billStatus.auditStatus, data.billStatus.approvalStatus).voidable)
    // },
    {
      name: "保存草稿",
      fun: "savedraft",
      show: computed(() => getBillStatus(data.billStatus.auditStatus, data.billStatus.approvalStatus).editable)
    },
    {
      name: "提交",
      fun: "submit",
      type: "primary",
      show: computed(() => getBillStatus(data.billStatus.auditStatus, data.billStatus.approvalStatus).editable)
    },
    {
      name: "评论",
      fun: "pinglun",
      type: "savedraft",
      show: computed(() => getBillStatus(data.billStatus.auditStatus, data.billStatus.approvalStatus).editable)
    }
  ],
  ReturnObject: [] as GoodsItem[],
  searchvalue: '',
  mobileDataNo: '',
  cCardno: '',
  isfromtable: false,
  uploadResults: [] as any[], // 存储上传结果
});

onShow(async () => {
  if (isBack) {
    data.fromlist.c_dname.value = storefromdata.value.c_dname
    data.fromlist.md.value = storefromdata.value.md
    receiptStore.setIsBack(false)
  }
});

const amountto = computed(() => {
  let len = data.ReturnObject.length || 0
  let amount = 0
  data.ReturnObject.map((item: GoodsItem) => {
    amount += parseInt(String(item.c_qtty || 0))
  })
  return `共${len}种/${amount}件`
})

interface ButtonCallback {
  fun: string;

  [key: string]: any;
}

const getcardno = async (cCardno: string) => {
  const result = await rdsRequest(
      rdsUrl.apiApi,
      '管易通60RMIS商品调拨',
      'GetUnSubmitDetail',
      {cCardno: cCardno, UserNo: mainStore.loginInfo.sUser}
  )
  let fromdata = {}
  result.ReturnObject.map((item: any, index: number) => {
    if (item.c_charger == 1) {
      fromdata = item
      result.ReturnObject.splice(index, 1)
    }
  })
  console.log('123123123', fromdata, result.ReturnObject)
  initfrom(fromdata)
  data.ReturnObject = result.ReturnObject
  receiptStore.replaceCartList(result.ReturnObject);
}
const callback = (btndata: ButtonCallback) => {
  let {fun} = btndata;
  methods[fun]();
};
const callbackfun = (callbackdata: ButtonCallback) => {
  methods[callbackdata.funname](callbackdata)
}
const uploadgoodcar = (e: number, item: GoodsItem) => {
  item.c_qtty = e
  receiptStore.updateCartItemQtty(item.c_gcode, e);
}
onLoad((options) => {
  if (options.cCardno) {
    data.cCardno = options.cCardno
    getcardno()
  }
  if (!data.cCardno) {
    data.ReturnObject = cartList
  }

  // getdata()
})
const initfrom = (fromdata: any) => {
  data.isfromtable = false
  data.fromlist.c_mk_dt.value = fromdata.c_dt
  data.fromlist.c_dname.value = fromdata.c_data2
  data.fromlist.md.value = fromdata.c_store_id
  data.fromlist.c_note.value = fromdata.c_note
  if (fromdata.c_cardno) {
    let cCardno = {
      label: '单据编号',
      type: 'text',
      value: fromdata.c_cardno,
      disabled: true
    }
    data.fromlist = {cCardno, ...data.fromlist}
    data.isfromtable = true
    console.log('123123123', data.fromlist)
  }
}
const methods: any = {
  // 提交
  async submit(type: string) {
    uni.showLoading({title: "提交中...", mask: true})
    await methods.savedraft('edit')
    console.log(data.mobileDataNo)
    let result = {
      "id": data.mobileDataNo, // 草稿单号
      "userNo": mainStore.loginInfo.sUser, //用户编号
    }
    const response = await rdsRequest(
        rdsUrl.apiApi,
        '管易通60RMIS商品调拨',
        'CreateGdsTuneBill',
        result
    );
    console.log(response)
    uni.navigateTo({
      url: `/pages/BusiViews/StoreTransfer/list`
    })

    uni.hideLoading()
  },
  //保存草稿
  async savedraft(type: string) {
    uni.showLoading({title: "保存中...", mask: true})
    const formData = fromtable.value.sub();
    let result = convertDraft(formData, data.ReturnObject, mainStore.loginInfo.sUser, mainStore.loginInfo.sUserStore);
    if (data.cCardno) {
      result.mobileDataNo = data.cCardno
    }
    console.log('result', result)
    const response = await rdsRequest(
        rdsUrl.apiApi,
        '管易通60RMIS商品调拨',
        'SaveOmGdss',
        result
    );
    data.mobileDataNo = response
    uni.hideLoading()
    if (!type) {
      uni.navigateTo({
        url: `/pages/BusiViews/StoreTransfer/list`
      })
    }
  },
  //添加商品
  addGoods() {
    uni.navigateTo({
      url: `/pages/BusiViews/CommonPage/search`
    })
  },
  //扫码添加商品
  scanthecode() {
    uni.navigateTo({
      url: `/pages/BusiViews/CommonPage/scanCodeByCommodity`
    })
  },
  //获取部门名称
  gednamet(callbackdata: any) {
    receiptStore.setIsBack(true)
    uni.navigateTo({
      url: `/pages/BusiViews/CommonPage/department`
    })

  },
  //获取门店
  getmd(callbackdata: any) {
    receiptStore.setIsBack(true)
    uni.navigateTo({
      url: `/pages/BusiViews/StoreTransfer/nearByStock`
    })
  },
  //评论
  pinglun() {
    refpopupfrom.value.open()
  }
};
const searchlist = (value: string) => {
  data.searchvalue = value
  let nl: GoodsItem[] = []
  data.ReturnObject.map((item: GoodsItem) => {
    if (item.c_name.includes(value)) {
      nl.push(item)
    }
  })
  data.isnodata = nl.length === 0
}
//反调拨选中回调
const checkout = (item: GoodsItem) => {
  console.log('item', item)
}
const filtervalue = (title: string) => {
  if (data.searchvalue && title.includes(data.searchvalue)) {
    return true
  } else if (!data.searchvalue) {
    return true
  } else {
    return false
  }
}
const cardchange = (fun: string) => {
  methods[fun]();
}
const getdata = async () => {
  uni.showLoading({title: "加载中...", mask: true})
  const result = await rdsRequest(
      rdsUrl.apiApi,
      '管易通60RMIS公共',
      'GetUserStoreDepart',
      {Id: mainStore.loginInfo.sUser}
  )
  let storedata = result.ds.map((ite: any) => {
    return {
      text: ite.c_name,
      value: ite.c_store_id
    }
  })
  let department = result.ds2.map((ite: any) => {
    return {
      text: ite.c_name,
      value: ite.c_adno
    }
  })
  // c_id: {
  //     label: "单据号",
  //     type: "text",
  //     value: "",
  //     disabled: true,
  //   },
  console.log('result', result)
  data.isfromtable = true
  uni.hideLoading()
}

interface GoodsItem {
  c_gcode: string;
  c_barcode: string;
  c_name: string;
  c_model: string;
  c_content: number;
  c_type: string;
  c_status: string;
  c_pro_status: string;
  c_sale_status: string;
  c_price: number;
  c_price_disc: number;
  c_number: number;
  c_today_sale: null;
  c_n_min: number;
  c_n_max: number;
  c_dnlmt_number: number;
  c_onway: number;
  c_to_ret: number;
  c_sn_perday_pro: number;
  c_dnlmt_day: number;
  c_sn_perday: number;
  c_n_min_order: number;
  c_opl_prohibit: null;
  c_week0: number;
  c_week1: number;
  c_week2: number;
  c_week3: number;
  c_week4: number;
  c_provider: string;
  c_provider_name: string;
  c_d_onway: null;
  c_qtty?: number; // 添加可选的数量字段
}

const {upload, remove, fetchFile} = useUpload({prefix: 'mainApi'});

const uploadimage = async (file: any) => {
  try {
    const result = await upload({
      file: {
        ext: file.tempFiles[0].name,
        url: file.tempFilePaths[0],
        name: file.tempFiles[0].name,
        type: file.tempFiles[0].fileType
      },
      uploadUserNo: mainStore.loginInfo.sUser
    });

    if (result) {
      // data.fromlist.sc.value.push({
      //   name: result.fileName,
      //   url: result.fileUrl
      // });

      data.uploadResults.push(result);
      console.log('所有上传结果:', data.uploadResults);
      console.log('当前上传结果:', result);
    }
    return result;
  } catch (error) {
    console.error('上传失败:', error);
    uni.showToast({
      title: '上传失败',
      icon: 'none'
    });
  }
};
// 添加表单禁用计算属性
const isFormDisabled = computed(() =>
    !getBillStatus(data.billStatus.auditStatus, data.billStatus.approvalStatus).editable
);
</script>

<style lang="scss" scoped>
page {
  overflow-y: hidden;
  height: 100vh;
}

.nav-bar-content {
  width: auto;
  height: 230rpx;
  background: white;

  image {
    width: 180rpx;
    height: 54rpx;
    gap: 30rpx;
  }
}

.card {
  border-radius: 16rpx;
  background-color: #ffffff;
  padding: 20rpx;
  margin-top: 20rpx;
}

.e-attachment {
  align-items: center;
  justify-content: center;
  display: flex;

  &__image {
    width: 230rpx;
    height: 230rpx;
    margin: 12rpx;
    border-radius: 10rpx;
  }
}

.tabs {
  height: 104rpx;
  background: #f2f3f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;

  .label {
    font-size: 32rpx;
    font-family: PingFang SC, PingFang SC-Semibold;
    font-weight: Semibold;
    text-align: center;
    color: #909399;
    text-align: center;
  }

  .active {
    font-size: 32rpx;
    font-family: PingFang SC, PingFang SC-Semibold;
    font-weight: Semibold;
    text-align: center;
    color: #303133;
    position: relative;

    &::after {
      content: "";
      display: block;
      width: 46rpx;
      height: 8rpx;
      background: #409eff;
      border-radius: 4rpx;
      position: absolute;
      bottom: -14rpx;
      left: 50%;
      margin-left: -23rpx;
    }
  }
}

.flex {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.first {
  margin-top: 10rpx;

  view {
    font-size: 24rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: Regular;
    text-align: left;
    color: #666666;
    line-height: 34rpx;
    margin-right: 40rpx;
  }
}

.second {
  margin-top: 10rpx;

  view {
    padding: 10rpx 15rpx;
    background: #f2f3f5;
    border-radius: 10rpx;
    font-size: 20rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: Regular;
    text-align: left;
    color: #666666;
    margin-right: 10rpx;
  }
}

.third {
  margin-top: 10rpx;

  view {
    font-size: 24rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: Regular;
    text-align: left;
    color: #666666;
    line-height: 40rpx;
    padding: 0 19rpx;
    position: relative;

    &::after {
      content: "";
      display: block;
      width: 2rpx;
      height: 20rpx;
      background: #dcdfe6;
      position: absolute;
      top: 50%;
      margin-top: -10rpx;
      right: 0;
    }

    &:last-child {
      &::after {
        content: "";
        display: none;
      }
    }
  }

}

.comhj {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 20rpx;
  position: relative;

  &::before {
    content: '';
    display: block;
    width: 670rpx;
    height: 2rpx;
    background: #f2f3f5;
    position: absolute;
    left: 50%;
    top: 0;
    margin-left: -335rpx;
  }

  view {
    font-size: 30rpx;
    font-family: PingFang SC, PingFang SC-Medium;
    font-weight: Medium;
    text-align: left;
    line-height: 42rpx;

    &:nth-child(1) {
      color: #222222;
    }

    &:nth-child(2) {
      color: #F56C6C;
    }
  }
}
</style>
